$(document).ready(function(){
    
    $("#search_term").keyup(function(){
        doSearch();
    });
    $("#search_cat").change(function(){
        doSearch();
    });
    
        
    doSearch();
        
});


function registerButtons(id){
    $("#delete_meal").click(function(e){
        e.preventDefault();
        if (confirm("Are you sure you wish to delete this meal?")){
            $.post(getBaseURL()+"meal_editing/edit_meals/deleteMeal",
                {meal_id: id},
                function(data){
                    location.reload();
                }
            );
        }
    });
}

function doSearch(){
    
    $("#search_results").html("");
    var search_term = $("#search_term").val();
    var search_cat = $("#search_cat").val();

    $.post(getBaseURL()+"meal_editing/edit_meals/searchResults/", 
        {
            search_term: search_term,
            category: search_cat
        },
        function(data){
            $("#search_results").html(data);
        }
    ); 
}

function selectMeal(elem, id){
    $('#search_results .listItem').removeClass('selected');
    $(elem).addClass('selected');
    $.post(getBaseURL()+"meal_editing/edit_meals/previewMeal/", 
        {meal_id: ""+id+""},
        function(data){
            $("#preview_meal").html(data);
            registerButtons(id);
        }
    );
}
